package com.charles.seckillGateway.service.impl;

import cn.hutool.core.util.IdUtil;
import com.charles.seckillGateway.service.CaptchaService;
import com.charles.seckillComponentCommon.constants.CacheConstants;
import com.charles.seckillComponentCommon.domain.AjaxResult;
import com.charles.seckillComponentCommon.exceptions.CaptchaException;
import com.charles.seckillComponentCommon.utils.Base64;
import com.charles.seckillComponentRedis.service.RedisService;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {
    
    @Resource(name = "captchaProducer")
    private Producer producer;

    @Autowired
    private RedisService redisService;
    
    @Override
    public AjaxResult createCaptcha() {
        AjaxResult success = AjaxResult.success();
        
        String uuid = IdUtil.fastSimpleUUID();
        String captchaVerifyKey = CacheConstants.CAPTCHA_TOKEN + uuid;
        String captchaCode = producer.createText();
        BufferedImage image = producer.createImage(captchaCode);

        // 有效期两分钟:
        redisService.setCacheObject(captchaVerifyKey, captchaCode, 2L, TimeUnit.MINUTES);
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) { 
            return AjaxResult.error(e.getMessage());
        }

        success.put("uuid", uuid);
        success.put("img", Base64.encode(os.toByteArray()));
        return success;
    }

    @Override
    public void verifyCaptcha(String code, String uuid) {
        if (code.isEmpty()) {
            throw new CaptchaException("验证码不能为空");
        }
        
        if (uuid.isEmpty()) {
            throw new CaptchaException("验证码已失效,点击验证码进行刷新");
        }

        String captchaVerifyKey = CacheConstants.CAPTCHA_TOKEN + uuid;
        String codeStr = redisService.getCacheObject(captchaVerifyKey);
        redisService.deleteObject(captchaVerifyKey);
        
        if (codeStr == null || codeStr.isEmpty()) {
            throw new CaptchaException("验证码已失效,点击验证码进行刷新");
        }
        
        if (!codeStr.equals(code)) {
            throw new CaptchaException("验证码错误，请重试");
        }

    }

}
